package cn.fzkj.ailangchain4j.tools;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * @ description
 * @ author yaya
 * @ since 2025/11/4
 */
@Slf4j
public class QueryTools {

    private static final String BASE_URL = "https://www.mianshiya.com/search/all?searchText=";
    private static final int TIMEOUT = 10000; // 10秒超时
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";

    @Tool(name = "interviewQuestionSearch", value = """
            Retrieves relevant interview questions from mianshiya.com based on a keyword.
            Use this tool when the user asks for interview questions about specific technologies,
            programming concepts, or job-related topics. The input should be a clear search term.
            """)
    public List<String> searchQuestions(@P(value = "the keyword to search") String keyword) {
        List<String> results = new ArrayList<>();

        try {
            // 构建完整的URL
            String url = BASE_URL + java.net.URLEncoder.encode(keyword, "UTF-8");

            // 使用Jsoup连接网站并获取HTML文档
            Document doc = Jsoup.connect(url)
                    .userAgent(USER_AGENT)
                    .timeout(TIMEOUT)
                    .get();

            // 根据面试鸭网站的实际HTML结构解析搜索结果
            // 这里需要根据网站的实际结构进行调整

            // 假设搜索结果包含在class为"question-item"的元素中
            Elements questionElements = doc.select(".ant-table-cell > a");

            if (questionElements.isEmpty()) {
                // 如果上面的选择器没有找到，尝试其他可能的选择器
                questionElements = doc.select("div[class*='question'], div[class*='result'], li, .list-item");
            }

            for (Element element : questionElements) {
                String questionText = extractQuestionText(element);
                if (questionText != null && !questionText.trim().isEmpty()) {
                    results.add(questionText);
                }

                // 限制返回结果数量，避免过多
                if (results.size() >= 10) {
                    break;
                }
            }

            // 如果没有找到结果，返回提示信息
            if (results.isEmpty()) {
                results.add("未找到与 '" + keyword + "' 相关的面试题目。请尝试其他关键词。");
            }

        } catch (Exception e) {
            // 处理各种异常情况
            results.add("搜索失败： " + e.getMessage());
            // 在实际项目中应该记录日志
            System.err.println("搜索面试题目时发生错误: " + e.getMessage());
        }

        return results;
    }

    /**
     * 从HTML元素中提取问题文本
     */
    private String extractQuestionText(Element element) {
        // 尝试多种可能的选择器来提取问题文本
        String[] possibleSelectors = {
                ".question-title", ".title", "h3", "h4", "a", ".content", ".text"
        };

        for (String selector : possibleSelectors) {
            Elements textElements = element.select(selector);
            if (!textElements.isEmpty()) {
                String text = textElements.first().text().trim();
                if (!text.isEmpty() && text.length() > 5) { // 过滤掉太短的文本
                    return text;
                }
            }
        }

        // 如果上面的选择器都没有找到，直接返回元素的文本
        String text = element.text().trim();
        return text.length() > 5 ? text : null;
    }

    /**
     * 增强版搜索方法，提供更详细的结果信息
     */
    @Tool(name = "搜索面试题目并返回详细结果，包括问题、答案和相关链接")
    public List<String> searchDetailedQuestions(@P(value = "the keyword to search") String keyword) {
        List<String> detailedResults = new ArrayList<>();

        try {
            String url = BASE_URL + java.net.URLEncoder.encode(keyword, "UTF-8");
            Document doc = Jsoup.connect(url)
                    .userAgent(USER_AGENT)
                    .timeout(TIMEOUT)
                    .get();

            Elements questionElements = doc.select(".question-item, .search-result, .question");

            int count = 0;
            for (Element element : questionElements) {
                if (count >= 5) break; // 限制详细结果数量

                StringBuilder result = new StringBuilder();
                result.append("问题 ").append(count + 1).append(": ");

                // 提取问题标题
                String title = extractQuestionText(element);
                if (title != null) {
                    result.append(title);
                }

                // 尝试提取答案或描述
                Elements answerElements = element.select(".answer, .description, .content");
                if (!answerElements.isEmpty()) {
                    String answer = answerElements.first().text();
                    if (answer.length() > 100) {
                        answer = answer.substring(0, 100) + "...";
                    }
                    result.append("\n答案: ").append(answer);
                }

                // 尝试提取链接
                Elements linkElements = element.select("a[href]");
                if (!linkElements.isEmpty()) {
                    String link = linkElements.first().attr("abs:href");
                    result.append("\n链接: ").append(link);
                }

                detailedResults.add(result.toString());
                count++;
            }

            if (detailedResults.isEmpty()) {
                detailedResults.add("未找到与 '" + keyword + "' 相关的详细面试题目。");
            }

        } catch (Exception e) {
            detailedResults.add("详细搜索失败: " + e.getMessage());
        }

        return detailedResults;
    }
}
